package com.yimi.yinhepda.views.offline.unload;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.pda.ym.base.BaseTitleActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.pda.ym.utils.ProvinceEnum;
import com.pda.ym.utils.CarNoSelectDialog;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;
import com.yimi.yinhepda.views.load_module.ScanSealSignActivity;

import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 离线卸车建立界面,
 *
 * @author lj
 */
public class OffLineUnloadCreateActivity extends BaseTitleActivity implements TextWatcher {

    /**
     * 配载单号
     */
    private EditText etStowageNo;
    /**
     * 任务号
     */
    private EditText etTaskNo;
    /**
     * 车牌
     */
    private Button btnCarPlate;
    /**
     * 车牌号
     */
    private EditText etCarNo;
    /**
     * 上一站
     */
    private TextView etPreDept;
    /**
     * 装卸车任务表操作类
     */
    private UnloadTaskTableDao taskTableDao;
    /**
     * 卸车标志
     */
    private int operTypeCode = 4;
    private String userCode;
    private String userName;
    private String preDeptCode;
    private String preDeptName;
    private String offlineTaskNo;
    private String lineType;
    private String preCompanyCode;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";

    @Override
    public String getPageName() {
        return "离线卸车建立";
    }

    public OffLineUnloadCreateActivity() {
        super(true);
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_offline_unload_create;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        etStowageNo = findViewById(R.id.et_stowageNo);
        etTaskNo = findViewById(R.id.et_taskNo);
        btnCarPlate = findViewById(R.id.btn_carPlate);
        btnCarPlate.setOnClickListener(this);
        etCarNo = findViewById(R.id.et_carNo);
        etCarNo.addTextChangedListener(this);
        etPreDept = findViewById(R.id.et_pre_dept);
        etPreDept.setOnClickListener(this);
        findViewById(R.id.btn_sure).setOnClickListener(this);

        taskTableDao = new UnloadTaskTableDao();
        userCode = sharedPreferUtil.getValue(Common.USER_CODE);
        userName = sharedPreferUtil.getValue(Common.USER_NAME);

        //设置车牌
        List<CarPlateTable> carPlateTables = new CarPlateTableDao().getAllData();
        if (carPlateTables != null && !carPlateTables.isEmpty()) {
            btnCarPlate.setText(carPlateTables.get(0).getCarPlate());
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result.contains(Common.SP_C_)) {
            etCarNo.setText(result.split(Common.SP_C_)[1]);
            btnCarPlate.setText(ProvinceEnum.getByCode(result.split(Common.SP_C_)[0]).getName());
            SoundVibratorManager.playSound(1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_carPlate:
                //显示车牌对话框提示框
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        btnCarPlate.setText(carPlate);
                    }
                });
                break;
            case R.id.et_pre_dept:
                Intent intent = new Intent(this, CreateDeptSelectActivity.class);
                intent.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                intent.putExtra("inputType", 2);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_sure:
                //确定按钮
                offlineUnloadCreateSubmit();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            preDeptCode = data.getStringExtra("deptCode");
            preDeptName = data.getStringExtra("deptName");
            lineType = data.getStringExtra("lineType");
            //选择的上一站
            preCompanyCode = data.getStringExtra("toCompany");
            if (preDeptCode == null || preDeptName == null) {
                etPreDept.setText("");
            } else {
                etPreDept.setText(preDeptName);
            }
            int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
            if ((deptType == 5 || deptType == 6) && lineType != null && lineType.equals("1")) {
                //当前登录为分拨且选择的为分拨（干线）
                etStowageNo.setText("");
                etStowageNo.setEnabled(false);
                etTaskNo.setEnabled(true);
            } else if ((deptType != 5 && deptType != 6) || lineType != null && lineType.equals("2")) {
                //当前登录为网点或者选择的为网点(支线)
                etTaskNo.setText("");
                etTaskNo.setEnabled(false);
                etStowageNo.setEnabled(true);
            }
        }
    }

    /**
     * 离线卸车建立提交
     */
    private void offlineUnloadCreateSubmit() {
//        int count = (int) new UnloadScanTableDao().queryCount("isUpload", 0, operTypeCode);
//        if (count > 9) {
//            Toast.makeText(this, "你的离线任务很多啊，兄弟", Toast.LENGTH_SHORT).show();
//            //开启扫描
//            setScannerEnabled(true);
//            SoundVibratorManager.playSound(2);
//            return;
//        }

        String carNo = etCarNo.getText().toString();
        if (carNo.equals("")) {
            showToast("请输入车牌号！");
            return;
        }
        String preDept = etPreDept.getText().toString();
        if (preDept.equals("")) {
            showToast("请选择上一站！");
            return;
        }
        String carPlate = btnCarPlate.getText().toString();
        String stowageNo = etStowageNo.getText().toString();

        //同样始发站-目的站-日期条件下，的order
        Integer order = taskTableDao.findByTime(DateHelper.getDateFormateShort(new Date()),
                preDeptCode, sharedPreferUtil.getDeptCode(), userCode);
        order = order == null ? 1 : order + 1;

        //离线任务号
        if (offlineTaskNo == null) {
            offlineTaskNo = "X" + DateHelper.getDateTimeFormateForSimple4(new Date()) + preDeptCode + order;
        }
        //创建配载单
        UnloadTaskTable taskTable = new UnloadTaskTable();
        taskTable.setTask(etTaskNo.getText().toString().trim());
        taskTable.setCreateTime(Constants.getCurrentTimeFormat1());
        taskTable.setShowTime(DateHelper.getDateFormateShort(new Date()));
        //车牌号
        taskTable.setCarNo(carPlate + carNo);
        //上一站code
        taskTable.setSrcDeptCode(preDeptCode);
        //上一站名称
        taskTable.setSrcDeptName(preDeptName);
        //选择的上一站
        taskTable.setToCompCode(preCompanyCode);
        //目的站code
        taskTable.setDestDeptCode(sharedPreferUtil.getDeptCode());
        //目的站名称
        taskTable.setDestDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
        // 序号
        taskTable.setOrder(order);
        //操作员工
        taskTable.setOperEmpCode(userCode);
        //操作员工 名称
        taskTable.setOperEmpName(userName);
        //干线，支线
        taskTable.setBizTypeCode(Integer.parseInt(lineType));
        //配载单
        taskTable.setStowageNo(stowageNo);
        //离线任务号
        taskTable.setOfflineTaskNo(offlineTaskNo);
        taskTable.setStatus(0);
        try {
            taskTableDao.insert(taskTable);
        } catch (SQLException e) {
            LogUtil.e(e.toString());
        }

        finish();

        //跳转至封签扫描界面
        Intent intent = new Intent(this, ScanSealSignActivity.class);
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        intent.putExtra("loadType", 2);
        intent.putExtra("offlineTaskNo", offlineTaskNo);
        intent.putExtra("carPlateNo", carPlate + carNo);
        intent.putExtra("lineType", lineType);
        startActivity(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //车牌号英文字母转换成大写
        String carNo = etCarNo.getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempCarNo)) {
            mTempCarNo = carNo;
            etCarNo.setText(carNo);
            etCarNo.setSelection(carNo.length());
        }
    }

    @Override
    public boolean showBack() {
        return true;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
